// index.js

const XLSX = require("../..//utils/xlsx.full.min")
Page({
  data: {
    motto: 'Hello World',
    openFileName: '',
    logNodes: [
       
    ],
  },

  // 事件处理函数
  handleClick() {
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: (res) => {
        //res.tempFiles[0] =>
        // {name: "ccc.xls", size: 30720, time: 1683474023, path: "http://tmp/TnCen6Pwewmbd2ea2347cb9f6642bac5abccc5fc27d6.xls", type: "file"}
        const {
          path,
          name
        } = res.tempFiles[0]
        this.setData({
          openFileName: name
        }, () => {
          this.readFile(path);
        })
      }
    });
  },

  readFile(filePath) {
    const fs = wx.getFileSystemManager()
    const data = fs.readFileSync(filePath, 'binary')
    const workbook = XLSX.read(data, {
      type: "binary"
    });
    const sheetName = workbook.SheetNames[0]
    const sheet = workbook.Sheets[sheetName]
    // 修改内容 XLSX.utils.sheet_add_aoa(sheet, [['new value']], { origin: 'D4' });

    const end = 40;
    const targetContentCellStartRowNum = 4;

    const bigPrice = 10;
    const pattern = /\d+(?:\.\d+)?/g;

    let totalOtherFee = 0;
    let totalLocalFee = 0;

    for (let index = targetContentCellStartRowNum; index < end + 1; index++) {
      const cell = sheet[`D${index}`];


      let cityTranFee = 0;
      let bus = 0;

      if (cell == null) {
        continue;
      }

      const cellString = cell.v;
      if (cellString != null && cellString === "") {
        const tempCell = sheet[XLSX.utils.encode_row(index)][XLSX.utils.encode_col(0)];

        if (tempCell.getStringCellValue().includes("小计")) {
          XLSX.utils.sheet_add_aoa(sheet, [
            [(totalOtherFee % 1 === 0) ? parseInt(totalOtherFee) : totalOtherFee]
          ], {
            origin: `G${index}`
          });
          XLSX.utils.sheet_add_aoa(sheet, [
            [(totalLocalFee % 1 === 0) ? parseInt(totalLocalFee) : totalLocalFee]
          ], {
            origin: `H${index}`
          });
          break;
        }
      }

      if (cellString != null && cellString.length > 0) {
        if (cellString.includes(".5")) {

          console.log("———————————————————————————");
          const query = wx.createSelectorQuery();
          query.select('#log-label').boundingClientRect();
          query.exec((res) => {
            const labelNode = res[0];
            const logNodes = [
              { text: '这是一条', style: 'color: green;' },
              { text: 'log信息', style: 'color: red;' },
            ];
            const nodes = logNodes.map((node) => {
              return `<span style="${node.style}">${node.text}</span>`;
            });
            this.data.logNodes = logNodes;
          });




          console.log(cellString);
        }

        const matcher = cellString.match(pattern);


        for (let i = 0; i < matcher.length; i++) {
          const matched = matcher[i];
          const value = parseFloat(matched);

          if (value >= bigPrice) {
            bus += value;
          } else {
            cityTranFee += value;
          }
        }

        if (cellString.includes(".5")) {
          console.log("异地交通费：" + bus);
          console.log("市内交通费：" + cityTranFee);
        }

        totalOtherFee += bus;
        totalLocalFee += cityTranFee;

        XLSX.utils.sheet_add_aoa(sheet, [
          [(bus % 1 === 0) ? parseInt(bus) : bus]
        ], {
          origin: `G${index}`
        });
        XLSX.utils.sheet_add_aoa(sheet, [
          [(cityTranFee % 1 === 0) ? parseInt(cityTranFee) : cityTranFee]
        ], {
          origin: `H${index}`
        });
        if (index === targetContentCellStartRowNum) {
          XLSX.utils.sheet_add_aoa(sheet, [
            [(bus % 1 === 0) ? parseInt(bus) : bus]
          ], {
            origin: `G${index}`
          });
          XLSX.utils.sheet_add_aoa(sheet, [
            [(cityTranFee % 1 === 0) ? parseInt(cityTranFee) : cityTranFee]
          ], {
            origin: `H${index}`
          });
        }
      }
    }
    return;
    console.log("———————————————————————————");
    // 表格修改完毕，准备另存为
    const workbook2 = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook2, sheet, 'Sheet1');
    this.outputFile(workbook2);
  },
  outputFile(workbook) {
    const fileData = XLSX.write(workbook, {
      bookType: "xlsx",
      type: 'base64'
    });
    const filePath = `${wx.env.USER_DATA_PATH}/edit_${this.data.openFileName}`
    const fs = wx.getFileSystemManager()
    fs.writeFile({
      filePath: filePath,
      data: fileData,
      encoding: 'base64',
      success: res => {
        console.log(res)
        const sysInfo = wx.getSystemInfoSync()
        if (sysInfo.platform.toLowerCase().indexOf('windows') >= 0) {
          wx.saveFileToDisk({
            filePath: filePath,
            success: console.log,
            fail: console.error
          })
        } else {
          wx.openDocument({
            filePath: filePath,
            showMenu: true, // 需要添加showMenu允许用户导出
            success: console.log,
            fail: console.error
          })
        }
      },
      fail: e => {
        console.error(e)
        if (e.errMsg.indexOf('locked')) {
          wx.showModal({
            title: '提示',
            content: '文档已打开，请先关闭',
          })
        }
      }
    })


  }
})